package com.player;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;

import static com.player.Data.*;

public class GetFrameFromFile {
    private final FFmpegFrameGrabber grabber;
    public GetFrameFromFile(String fileName) {



        grabber = new FFmpegFrameGrabber(fileName);
        try {
            grabber.start();

        } catch (FFmpegFrameGrabber.Exception e) {
            throw new RuntimeException(e);
        }
        width = grabber.getImageWidth();
        height = grabber.getImageHeight();
        TIMESTAMP = grabber.getLengthInTime();
        System.out.println("音频采样率"+grabber.getSampleRate());
        System.out.println("音频通道数"+grabber.getAudioChannels());

    }
    public FFmpegFrameGrabber getFrameGrabber() {
        return grabber;
    }




    public void run() {
        try {

            Frame frame;
            while ((frame = grabber.grabFrame())!=null) {
                if (frame.type == Frame.Type.AUDIO) {
                    var newFrame = frame.clone();
                    frame.close();
                    AUDIO_QUEUE.put(newFrame);
                }else if (frame.type == Frame.Type.VIDEO) {
                    var newFrame = frame.clone();
                    frame.close();
                    VIDEO_QUEUE.put(newFrame);
                }
            }
            closed.set(true);

        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        finally {
            try {
                grabber.close();
            } catch (FrameGrabber.Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
